package com.baiyun.yunpan.controller;

import com.baiyun.yunpan.entity.User;
import com.baiyun.yunpan.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.baiyun.yunpan.Util.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Sam
 * @date 2021/5/22 21:31
 */


@RestController
@RequestMapping("user")
@CrossOrigin(origins = "*", maxAge = 3600)
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 用户注册
     * @param user
     * @return 返回成功信息
     */
    @PostMapping("reg")
    public String reg(User user) throws Exception {


        if(user.getUsername().equals("")){
            return "用户名不能为空";
        }
        if (user.getPassword().equals("")){
            return "密码不能为空";
        }
        if ( userService.getUserByName(user)!=null){
            return "账号已存在";
        }
        user.setRegistertime(new Date());
        userService.reg(user);
        return "success";
    }

    /**
     * 用户登陆
     * @param user
     * @return
     */
    @PostMapping("login")
    public Object login(User user) throws Exception {
        if(user.getUsername().equals("")){
            return "用户名不能为空";
        }
        if (user.getPassword().equals("")){
            return "密码不能为空";
        }

        User users =userService.login(user);

        if (users==null){
            return "用户名和密码不匹配";
        }
        Map<String,String> payload = new HashMap<>();
        payload.put("name",users.getUsername());
        users.setPassword(JWTUtils.getToken(payload));
        return users;

    }

    /**
     * 根据用户id查询用户信息
     * @param id
     * @return
     */
    @GetMapping("getUser")
    public Object getUser(int id ){

        return userService.getUserBy(id);
    }

    @GetMapping("update")
    public Object update(User users){


        if (users.getRealname().equals("")){
            return "真实姓名不能为空";
        }
        userService.uodate(users);
        return "修改成功";
    }


}
